package server

import (
	"net/http"
	"cve-db/db"
	"github.com/gin-gonic/gin"
)

func Start(driver db.DB, bind string, port string) {
	router := gin.Default()
	// Routes
	router.GET("/cves/:id", getCve(driver))
	router.POST("/cpes", getCveByCpeName(driver))
	router.POST("/cpes/ids", getCveIDsByCpeName(driver))
	var addr string
	if bind != "" && port != "" {
		addr = bind + ":" + port
	} else if bind != "" {
		addr = bind + ":" + "8000"
	} else if port != "" {
		addr = ":" + port
	} else {
		addr = ":8000"
	}
	router.Run(addr)
}

// Handler
func getCve(driver db.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		cveid := c.Param("id")
		cveDetail, err := driver.Get(cveid)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"error":  err.Error(),
			})
		}
		c.JSON(http.StatusOK, &cveDetail)
	}
}

type cpeName struct {
	Name string `form:"name"`
}

func getCveByCpeName(driver db.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		cpe := cpeName{}
		err := c.ShouldBind(&cpe)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"error":  err.Error(),
			})
		}
		cveDetails, err := driver.GetByCpeURI(cpe.Name)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"error":  err.Error(),
			})
		}
		c.JSON(http.StatusOK, &cveDetails)
	}
}

func getCveIDsByCpeName(driver db.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		cpe := cpeName{}
		err := c.ShouldBind(&cpe)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"error":  err.Error(),
			})
		}
		cveIDs, err := driver.GetCveIDsByCpeURI(cpe.Name)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"error":  err.Error(),
			})
		}
		c.JSON(http.StatusOK, &cveIDs)
	}
}
